{
 "cells": [
  {
   "cell_type": "raw",
   "id": "d9f57826",
   "metadata": {},
   "source": [
    "---\n",
    "sidebar_position: 0\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e10aa932",
   "metadata": {},
   "source": [
    "# OpenAI tools\n",
    "\n",
    "Certain OpenAI models have been finetuned to work with with **tool calling**. This is very similar but different from **function calling**, and thus requires a separate agent type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ec89be68",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ! pip install openai tavily-python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b812b982",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_openai_tools_agent\n",
    "from langchain_community.chat_models import ChatOpenAI\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ef71dfc-074b-409a-8451-863feef937ae",
   "metadata": {},
   "source": [
    "## Initialize Tools\n",
    "\n",
    "For this agent let's give it the ability to search the web with Tavily."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "23fc0aa6",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [TavilySearchResults(max_results=1)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fc45217",
   "metadata": {},
   "source": [
    "## Create Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2e6353c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/openai-tools-agent\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "28b6bb0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Choose the LLM that will drive the agent\n",
    "# Only certain models support this\n",
    "llm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", temperature=0)\n",
    "\n",
    "# Construct the OpenAI Tools agent\n",
    "agent = create_openai_tools_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1146eacb",
   "metadata": {},
   "source": [
    "## Run Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c6d4e9b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "7bf0c957",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': 'LangChain'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.ibm.com/topics/langchain', 'content': 'LangChain is essentially a library of abstractions for Python and Javascript, representing common steps and concepts  LangChain is an open source orchestration framework for the development of applications using large language models  other LangChain features, like the eponymous chains.  LangChain provides integrations for over 25 different embedding methods, as well as for over 50 different vector storesLangChain is a tool for building applications using large language models (LLMs) like chatbots and virtual agents. It simplifies the process of programming and integration with external data sources and software workflows. It supports Python and Javascript languages and supports various LLM providers, including OpenAI, Google, and IBM.'}]\u001b[0m\u001b[32;1m\u001b[1;3mLangChain is an open source orchestration framework for the development of applications using large language models. It is essentially a library of abstractions for Python and Javascript, representing common steps and concepts. LangChain simplifies the process of programming and integration with external data sources and software workflows. It supports various large language model providers, including OpenAI, Google, and IBM. You can find more information about LangChain on the IBM website: [LangChain - IBM](https://www.ibm.com/topics/langchain)\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is an open source orchestration framework for the development of applications using large language models. It is essentially a library of abstractions for Python and Javascript, representing common steps and concepts. LangChain simplifies the process of programming and integration with external data sources and software workflows. It supports various large language model providers, including OpenAI, Google, and IBM. You can find more information about LangChain on the IBM website: [LangChain - IBM](https://www.ibm.com/topics/langchain)'}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80ea6f1b",
   "metadata": {},
   "source": [
    "## Using with chat history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "178e561d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mYour name is Bob.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name? Don't use tools to look this up unless you NEED to\",\n",
       " 'chat_history': [HumanMessage(content='hi! my name is bob'),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'output': 'Your name is Bob.'}"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "\n",
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"input\": \"what's my name? Don't use tools to look this up unless you NEED to\",\n",
    "        \"chat_history\": [\n",
    "            HumanMessage(content=\"hi! my name is bob\"),\n",
    "            AIMessage(content=\"Hello Bob! How can I assist you today?\"),\n",
    "        ],\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "120576eb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
